package com.lib.servlet.admin;

import com.alibaba.fastjson.JSON;
import com.lib.common.Constant;
import com.lib.dao.AdminDao;
import com.lib.entity.Admin;
import com.lib.entity.JsonResult;
import com.lib.service.AdminService;
import com.lib.service.ex.EmptyArgumentException;
import com.lib.service.ex.LoginException;
import com.lib.service.ex.ServiceException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "AdminLoginServlet", value = "/admin/AdminLoginServlet.do")
public class AdminLoginServlet extends HttpServlet {
    private AdminService adminService = new AdminService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String pwd = request.getParameter("pwd");
        Admin admin = null;
        JsonResult jsonResult = null;
        try {
            admin = adminService.login(name,pwd);
            request.getSession().setAttribute(Constant.SESSION_ADMIN,admin);
            jsonResult = JsonResult.getSuccessJR(admin);
        } catch (EmptyArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (LoginException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_LOGIN,e.getMessage());
        } catch (ServiceException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_ERROR,e.getMessage());
        }

        System.out.println("---------------------->jsonresult"+ JSON.toJSONString(jsonResult));
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(jsonResult));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
